package com.xiaoxiao.spring.bean;

import com.xiaoxiao.spring.web.HandlerMapping;
import com.xiaoxiao.spring.web.annotaition.Controller;

import java.io.File;
import java.net.URL;


public class DefaultBeanFactory implements BeanFactory {

	@Override
	public void initContainer(Class<?> clazz) {
		ClassLoader classLoader = clazz.getClassLoader();
		initContainerFromFolder(classLoader, clazz.getPackage().getName());
	}

	private static void initContainerFromFolder(ClassLoader classLoader, String packName) {
		URL url = classLoader.getResource(packName.replace(".", "/"));
		File file = new File(url.getPath());
		File[] files = file.listFiles();
		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory()) {
				initContainerFromFolder(classLoader, packName + "." + files[i].getName());
			} else if (files[i].getName().endsWith(".class")) {
				try {
					Class<?> clazz = Class.forName(packName + "." + files[i].getName().replace(".class", ""));
					initMvcMapping(clazz);
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private static void initMvcMapping(Class<?> clazz){
		if (clazz.getAnnotation(Controller.class) != null) {
			HandlerMapping.addHandler(clazz);
		}
	}
}
